# -*- coding: utf-8 -*-
import tornado.httpserver
import tornado.httpclient
import tornado.ioloop
import tornado.web
import MySQLdb,os
import simplejson as json
import sys
import socket
import string
from types import *

"""
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
#readbuffer=""
"""
"""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
"""
g_title = ""
g_cloud_info = ""
g_cloud_slogan = ""
g_home = ""
g_forum = ""
g_translate = ""
g_fuckml = ""
g_chat = ""
piece = ""
conn = MySQLdb.connect (host = "localhost", user = "www-data", passwd = "",db = "ncpt")
cursor = conn.cursor ()
cursor.execute("SET NAMES utf8")

def gen_unique_id(ip):
	ip = string.replace( ip ,".", "0" )
	n = str((int(ip)/4 - 100)*3)
	x = (int(n[:4]) + int(n[-5]))
	return x
	
def def_title(lang):
	global g_title, g_cloud_info,g_cloud_slogan,g_home,g_forum,g_translate,g_fuckml,g_chat,g_url_home,g_url_forum,g_url_translate,g_url_chat,g_url_fuckml
	g_url_home = "/?lang=" + str(lang)
	g_url_forum = "/forum/board?lang=" + str(lang)
	g_url_translate = "/forum/translate?lang=" + str(lang)
	g_url_chat = "#" + str(lang)
	g_url_fuckml = "/forum/fuckml?lang=" + str(lang)
	if (lang == "en"):
		g_title = "Welcome to Cloudyama"
		g_cloud_info = "Cloudyama.com"
		g_cloud_slogan = "International Students @ Japan "
		g_home = "home"
		g_forum = "forums"
		g_translate = "human translation"
		g_fuckml = "fuck my life"
		g_chat = "chat"

	if (lang == "jp"):
		g_title = "雲山へようこそ"
		g_cloud_info = "Cloudyama.com"
		g_cloud_slogan = "日本の国際学生"
		g_home = "ホーム"
		g_forum = "掲示板"
		g_translate = "人力翻訳"
		g_fuckml = "この野郎"
		g_chat = "チャット"
		
	if (lang == "cn"):
		g_title = "欢迎来到云山"
		g_cloud_info = "Cloudyama.com"
		g_cloud_slogan = "在日本的国际学生"
		g_home = "首页"
		g_forum = "论坛"
		g_translate = "人肉翻译"
		g_fuckml = "我靠！"
		g_chat = "聊天"
		
class MainHandler(tornado.web.RequestHandler):
	def get(self):
		try:
			req_lang = str(self.get_argument('lang'))
		except Exception,e:
			self.render("cloud/top.html")
			return
	#Oh yes, this is where you start all the Google Applications Engine shit !!! Yeah !
	#And there is no one allowed to use IE!!!!
		title = ""
		script = "js/hp-"+ str(req_lang) + ".js"
		#this is the blog part
		cursor.execute ("""
				SELECT title, time, body, id
				FROM cloud_titan
				WHERE lang = %s
				ORDER BY time DESC
				LIMIT 20
				""",req_lang)
		rows = cursor.fetchall()
		#here comes the forum and other parts
		cursor.execute ("""
				SELECT title,id
				FROM cloud_forum
				WHERE lang = %s
				ORDER BY time DESC
				LIMIT 5
				""",req_lang)
		rows_forum = cursor.fetchall()
		cursor.execute ("""
				SELECT body,id
				FROM cloud_fml
				WHERE lang = %s
				ORDER BY time DESC
				LIMIT 1
				""",req_lang)
		rows_fml = cursor.fetchall()
		cursor.execute ("""
				SELECT body,id
				FROM cloud_translate
				WHERE lang = %s
				ORDER BY time DESC
				LIMIT 5
				""",req_lang)
		rows_translate = cursor.fetchall()
		#end of that part
		client_ip = str(self.request.remote_ip)
		gen_unique_id(client_ip)
		def_title(str(req_lang))
		if (req_lang == 'en'):
			languages = "<li><a href = '/?lang=jp'>日本語</a></li>"
			like = "Like"
			dislike = "Dislike"
			speak = "Say Something"
			ladder = "Close Header"
			facebook = "Find us on Facebook"
			twitter = "Follow us"
			translation = "Translation!"
			self_intro = "People @ Twitter"
			fml = "FML @ Japan"
			reply_text = " comment "
			headblock = ""
			#headblock = "<object width='640' height='385'><param name='movie' value='http://www.youtube.com/v/7nUYehygvvU&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/7nUYehygvvU&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='640' height='385'></embed></object>"
		elif (req_lang == 'jp'):
			languages = "<li><a href = '/?lang=en'>English</a></li>"
			like = "好き"
			dislike = "違う"
			speak = "つぶやく"
			ladder = "トップを閉じる"
			facebook = "フェスブックで見つける"
			twitter = "フォーロ"
			translation = "これを翻訳して"
			self_intro = "国際学生@Twitter"
			fml = "最新この野郎"
			reply_text = " コメントする "
			headblock = ""
			#headblock = "<object width='640' height='385'><param name='movie' value='http://www.youtube.com/v/bN-mlaeSYOo&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/bN-mlaeSYOo&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='640' height='385'></embed></object>"
		elif (req_lang == 'cn'):
			languages = "<li><a href = '/?lang=jp'>日本語</a></li><li><a href = '/?lang=en'>English</a></li>"
			title = "歡迎來到雲山"
			cloud_info = "Cloudyama.com"
			cloud_slogan = "在日本的國際學生"
			home = "首頁"
			like = "頂"
			dislike = "踩"
			speak = "隨邊說說"
			ladder = "排行"
		else:
			self.write("No such request!")
			return
		#other parts just came!!
		blogs = []
		forum_heads = []
		fml_heads = []
		translation_heads = []
		for row in rows:
			mon = str(row[1])[5:7]
			tm = str(row[1])[-8:]
			dayy = str(row[1])[-11:-8]
			dic_mon = {'01':'Jan','02':'Feb','03':'Mar','04':'Apr','05':'May',
				'06':'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov',
				'12':'Dec'}
			mon = dic_mon[mon]
			blogs.append( str(row[0]) + "<em>{</em><li>" + str(row[2]) + 
				"</li>" + "<li><span id ='mon'>" + mon  + "<span id ='dayy'>" + dayy + "</span></span><span id ='tm'>"+ tm + "</span></li><p><em>}</em>" + 
				"<a href = 'http://211.6.189.194:8888/titan/contents?id=" + str(row[3])
				+ "'>" + reply_text + "</a><em>{</em></p>")
		row = ""
		for row in rows_forum:
			forum_heads.append( "<a href = 'http://211.6.189.194:8888/forum/contents?id=" + str(row[1]) + "&lang=" + req_lang 
				+ "'>" + str(row[0][:35]) + " ...</a>")
		row = ""
		for row in rows_translate:
			translation_heads.append( "<a href = 'http://211.6.189.194:8888/forum/translate?id=" + str(row[1]) + "&lang=" + req_lang 
				+ "'>" + str(row[0][:35]) + " ...</a>")
		row = ""
		for row in rows_fml:
			fml_heads.append( str(row[0]) + "<li>" + "</li><p>" + 
				"<a href = 'http://211.6.189.194:8888/forum/fuckml?id=" + str(row[1]) + "&lang=" + req_lang
				+ "'>" + reply_text + "</a></p>")
		self.render("cloud/hp-en.html", 
			translation_heads = translation_heads,
			forum_heads = forum_heads,
			fml_heads = fml_heads,
			headblock = headblock,
			title = g_title,
			blogs = blogs,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			languages = languages,
			script = script,
			#urls - Start
			home = g_home,
			url_home = g_url_home,
			forum = g_forum,
			url_forum = g_url_forum,
			translate = g_translate,
			url_translate = g_url_translate,
			fuckml = g_fuckml,
			url_fuckml = g_url_fuckml,
			chat = g_chat,
			url_chat = g_url_chat,
			#urls - End
			like = like,
			dislike = dislike,
			speak = speak,
			ladder = ladder, 
			facebook = facebook,
			twitter = twitter,
			translation = translation,
			self_intro = self_intro,
			fml = fml )

class ChatHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
    	s=socket.socket( )
	s.connect((HOST, PORT))
	s.send("NICK %s\r\n" % NICK)
	s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))	
	while 1:	
		readbuffer = ""	
		readbuffer=readbuffer+s.recv(1024)
    		temp=string.split(readbuffer, "\n")	
		readbuffer=temp.pop()	
		self.write(str(temp))	
		for line in temp:
        		line=string.rstrip(line)
        		line=string.split(line)
        		if(line[0]=="PING"):	
				s.send("PONG %s\r\n" % line[1])        
		self.finish()
class AdminBlogHandler(tornado.web.RequestHandler):
	def get(self,req_id):
		if req_id == "board":
			def_title('cn')
			forum_title_text = "最新日志"
			forum_time_text = "最后更新"
			id = ""
			titan = "回去论坛/掲示板に戻る/Go back to forum"
			languages = "<a href = '#'>道可道非常道</a>"
			script = "js/forum-cn.js"
			cursor.execute ("""
					SELECT title, time, id 
					FROM cloud_titan
					ORDER BY time DESC
					LIMIT 20
					""")
			rows = cursor.fetchall()
			topics = []
			file = "cloud/titan.html"
			for row in rows:
				topics.append("<a href = '/titan/contents?id="+ str(row[2]) + "'>"+ str(row[0]) + "</a>" + "<li>" + str(row[1]) + "</li>")
		if req_id == "contents":
			file = "cloud/titan-contents.html"
			req_id = str(self.get_argument('id'))
			forum_title_text = ""
			forum_time_text = "Last updated"
			titan = "Home／ホーム"
			languages = "<a href = '/forum/contents?lang=jp&id=" + req_id + "'>日本語</a><a href = '/forum/contents?lang=en&id="+ req_id + "'>English</a>"
			script = "js/contents-cn.js"
			cursor.execute ("""
					SELECT body, time
					FROM cloud_titan
					WHERE id = %s
					""",req_id)
			piece = cursor.fetchone()
			cursor.execute ("""
					SELECT body, time 
					FROM cloud_titan_replies
					WHERE topic_id = %s
					ORDER BY time DESC
					""",req_id)
			rows = cursor.fetchall()
			topics = []
			id = req_id
			topics.append("<a>" + str(piece[0]) + "<em>" + str(piece[1]) + "</em>""</a>")
			for row in rows:
				topics.append("<a>"+ str(row[0]) + "<em>" + str(row[1]) + "</em>""</a>")
		self.render(file,
			#Local Items
			id = id,
			forum_time_text = forum_time_text,
			forum_title_text = forum_title_text,
			topics = topics,
			url_forum = "/?lang=en",
			titan = titan,
			#Under are all commons
			title = g_title,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			home = g_home,
			forum = g_forum,
			translate =  g_translate,
			fuckml = g_fuckml,
			chat = g_chat,
			script = script,
			languages = languages)

class ForumHandler(tornado.web.RequestHandler):
	def get(self,req):
		useragent = str(self.request.headers)
		n = string.find(useragent, 'MSIE')
		if n <> -1:
			self.render("cloud/html/error/browser.html")
			return
		if req == "board":
			css = ""
			req_lang = str(self.get_argument('lang'))
			def_title(req_lang)
			if req_lang == "en":
				forum_title_text = "All Topics:"
				forum_time_text = "Unique ID  |  Last updated"
				titan = "titan's blog<span> }</span><p>Sticky Link</p><br><em>the official blog of the website</em></br>"
			elif req_lang == "jp":
				forum_title_text = "スレッド："
				forum_time_text = "ユニックID  |  最新更新"
				titan = "タイタンのブログ<span> }</span><p>固定リンク</p><br><em>公式サイトボログ</em></br>"
			languages = "<a href = '/forum/board?lang=jp'>日本語</a><a href = '/forum/board?lang=en'>English</a>"
			script = "js/forum-"+ str(req_lang) + ".js"
			cursor.execute ("""
					SELECT title, time, id, uid
					FROM cloud_forum
					WHERE lang = %s
					ORDER BY time DESC
					LIMIT 20
					""",req_lang)
			rows = cursor.fetchall()
			topics = []
			id = ""
			file = "cloud/forum.html"
			for row in rows:
				topics.append("<a href = '/forum/contents?id="+ str(row[2]) + "&lang=" + req_lang + "'>"+ str(row[0]) 
					+ "<p>" + str(row[3]) + "<span> | </span>" + str(row[1]) + "</p></a>")
		elif req == "contents":
			file = "cloud/content.html"
			req_id = str(self.get_argument('id'))
			req_lang = str(self.get_argument('lang'))
			def_title(req_lang)
			css = "css/styles-content.css"
			if req_lang == "en":
				forum_title_text = ""
				forum_time_text = "Last updated"
				titan = "Go back to forum"
			elif req_lang == "jp":
				forum_title_text = ""
				forum_time_text = "最新更新"
				titan = "掲示板に戻る"
			languages = "<a href = '/forum/contents?lang=jp&id=" + req_id + "'>日本語</a><a href = '/forum/contents?lang=en&id="+ req_id + "'>English</a>"
			script = "js/contents-"+ str(req_lang) + ".js"
			cursor.execute ("""
					SELECT body, time
					FROM cloud_forum
					WHERE id = %s
					""",req_id)
			piece = cursor.fetchone()
			cursor.execute ("""
					SELECT body, time FROM cloud_replies
					WHERE topic_id = %s
					ORDER BY time ASC
					""",req_id)
			rows = cursor.fetchall()
			topics = []
			id = req_id
			topics.append("<a>" + str(piece[0]) + "<em>" + str(piece[1]) + "</em>""</a>")
			for row in rows:
				topics.append("<a>"+ str(row[0]) + "<em>" + str(row[1]) + "</em>""</a>")
		elif req == "fuckml":
			req_lang = str(self.get_argument('lang'))
			def_title(req_lang)
			css = ""
			file = "cloud/fml.html"
			#from here we define all the local variables
			#things that I do not use
			titan = ""
			if req_lang == "en":
				forum_title_text = "<span>{ </span>all the things that are FUCKED UP today<span> }</span>"
				forum_time_text = "Last updated"
			elif req_lang == "jp":
				forum_title_text = "<span>{ </span>最新この野郎<span> }</span>"
				forum_time_text = "最新更新"
			languages = "<a href = '/forum/fuckml?lang=jp'>日本語</a><a href = '/forum/fuckml?lang=en'>English</a>"
			script = "js/fml-"+ str(req_lang) + ".js"
			#start to fetch things here.
			cursor.execute ("""
					SELECT body, time, id, uid
					FROM cloud_fml
					WHERE lang = %s AND depth = 0
					ORDER BY time DESC
					LIMIT 20
					""",req_lang)
			rows = cursor.fetchall()
			topics = []
			id = ""
			for row in rows:
				topics.append("<a href = '/forum/contents_fml?id="+ str(row[2]) + "&lang=" + req_lang + "'>"+ str(row[0]) 
					+ "<p>" + str(row[3]) + "<span> | </span>" + str(row[1]) + "</p></a>")
		elif req == "translate":
			css = ""
			req_lang = str(self.get_argument('lang'))
			def_title(req_lang)
			file = "cloud/translate.html"
			titan = ""
			#from here we define all the local variables
			if req_lang == "en":
				forum_title_text = "<span>{ </span>SOME ONE TRASNLATE THIS SHIT FOR ME !!<span> }</span>"
				forum_time_text = "Last updated"
			elif req_lang == "jp":
				forum_title_text = "<span>{ </span>だれがこれを翻訳してくれ！<span> }</span>"
				forum_time_text = "最新更新"
			languages = "<a href = '/forum/translate?lang=jp'>日本語</a><a href = '/forum/translate?lang=en'>English</a>"
			script = "js/translate-"+ str(req_lang) + ".js"
			cursor.execute ("""
					SELECT body, time, id, uid
					FROM cloud_translate
					WHERE lang = %s AND depth = 0
					ORDER BY time DESC
					LIMIT 20
					""",req_lang)
			rows = cursor.fetchall()
			topics = []
			id = ""
			for row in rows:
				topics.append("<a href = '/forum/contents_translate?id="+ str(row[2]) + "&lang=" + req_lang + "'>"+ str(row[0]) 
					+ "<p>" + str(row[3]) + "<span> | </span>" + str(row[1]) + "</p></a>")
		elif (req == "contents_fml") or (req == "contents_translate"):
			file = "cloud/content.html"
			req_id = str(self.get_argument('id'))
			req_lang = str(self.get_argument('lang'))
			languages = "<a href = '/forum/" + req + "?lang=jp&id=" + req_id + "'>日本語</a><a href = '/forum/"+ req + "?lang=en&id="+ req_id + "'>English</a>"
			def_title(req_lang)
			if req == "contents_fml":
				g_url_forum = "fuckml?lang=" + req_lang
				css = "css/styles-fml-contents.css"
				script = "js/contents-"+ str(req_lang) + ".js"
				cursor.execute ("""
					SELECT body, time
					FROM cloud_fml
					WHERE id = %s AND depth = 0
					""",req_id)
				piece = cursor.fetchone()
				cursor.execute ("""
					SELECT body, time FROM cloud_fml
					WHERE id = %s AND depth = 1
					ORDER BY time ASC
					""",req_id)
				rows = cursor.fetchall()
				if req_lang == "en":
					forum_title_text = ""
					forum_time_text = "Last updated"
					titan = "Go back to fml"
				elif req_lang == "jp":
					forum_title_text = ""
					forum_time_text = "最新更新"
					titan = "このやろうに戻る"
			else:
				g_url_forum = "translate?lang=" + req_lang
				css = "css/styles-translate-contents.css"
				script = "js/contents-"+ str(req_lang) + ".js"
				cursor.execute ("""
					SELECT body, time
					FROM cloud_translate
					WHERE id = %s AND depth = 0
					""",req_id)
				piece = cursor.fetchone()
				cursor.execute ("""
					SELECT body, time FROM cloud_translate
					WHERE id = %s AND depth = 1
					ORDER BY time ASC
					""",req_id)
				rows = cursor.fetchall()
				if req_lang == "en":
					forum_title_text = ""
					forum_time_text = "Last updated"
					titan = "Go back to translation"
				elif req_lang == "jp":
					forum_title_text = ""
					forum_time_text = "最新更新"
					titan = "人力翻訳に戻る"
			global g_url_forum
			topics = []
			id = req_id
			topics.append("<a>" + str(piece[0]) + "<em>" + str(piece[1]) + "</em>""</a>")
			for row in rows:
				topics.append("<a>"+ str(row[0]) + "<em>" + str(row[1]) + "</em>""</a>")
		self.render(file,
			#Local Items
			forum_time_text = forum_time_text,
			forum_title_text = forum_title_text,
			topics = topics,
			titan = titan,
			id = id,
			#Under are all commons
			css = css,
			title = g_title,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			home = g_home,
			forum = g_forum,
			translate =  g_translate,
			fuckml = g_fuckml,
			chat = g_chat,
			script = script,
			languages = languages,
			url_home = g_url_home,
			url_forum = g_url_forum,
			url_translate = g_url_translate,
			url_chat = g_url_chat,
			url_fuckml = g_url_fuckml)

class InfoHandler(tornado.web.RequestHandler):
	def post(self, data):
		#the correct way of getting a remote ip. and handle that later.
		client_ip = str(self.request.remote_ip)
		uid = gen_unique_id(client_ip)
		if data == "":
			lang = self.get_argument("lang").encode("utf-8","ignore")
			title = self.get_argument("title").encode("utf-8","ignore")
			body = self.get_argument("body").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_forum
						ORDER BY id DESC
						LIMIT 1""")
			row = cursor.fetchone()
			last_forum_id = int(row[0]) + 1
			cursor.execute("""INSERT INTO cloud_forum
						VALUES (%s, %s, %s, %s,CURRENT_TIMESTAMP,%s)
						""", (title, body,last_forum_id,lang,uid))
			output = "Post Success!"
		elif data == "titan":
			title = self.get_argument("title").encode("utf-8","ignore")
			lang = title[5:7]
			body = self.get_argument("body").encode("utf-8","ignore")
			if (body[:17] <> "password:ododlaed") or (title[:4] <> "lang"):
				output = "休想发布任何消息！STAY WHILE YOU ENJOY YOUR LAST MOMENTS!!"
			else:
				cursor.execute("""
						SELECT id FROM cloud_titan
						ORDER BY id DESC
						LIMIT 1""")
				row = cursor.fetchone()
				last_titan_id = int(row[0]) + 1
				cursor.execute("""INSERT INTO cloud_titan
							VALUES (%s, %s, %s, %s,CURRENT_TIMESTAMP)
							""", (title[7:], body[17:],last_titan_id,lang,))
				output = "我果然是天才！居然不知道你是谁！"
		elif data == "reply":
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_replies
						WHERE topic_id = %s
						ORDER BY id DESC
						LIMIT 1""",(id))
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			cursor.execute("""INSERT INTO cloud_replies
						VALUES (%s, %s,CURRENT_TIMESTAMP, %s, %s)
						""", (id, body,last_titan_id,uid))
			cursor.execute("""
							UPDATE cloud_forum
							SET time = CURRENT_TIMESTAMP
							WHERE id = %s
							""",id)
			output = "Post Success!"
		elif data == "replytitan":
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_titan_replies
						WHERE topic_id = %s
						ORDER BY id DESC
						LIMIT 1""",(id))
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			cursor.execute("""INSERT INTO cloud_titan_replies
						VALUES (%s, %s,CURRENT_TIMESTAMP, %s, %s)
						""", (id, body,last_titan_id,uid))
			output = "Post Success!"
		elif (data == "fml") or (data == "translate"):
			db_table = "cloud_" + str(data)
			lang = self.get_argument("lang").encode("utf-8","ignore")
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			print db_table	
			if data == "fml":	
				cursor.execute("""SELECT id FROM cloud_fml ORDER BY id DESC LIMIT 1""")
			else:
				cursor.execute("""SELECT id FROM cloud_translate ORDER BY id DESC LIMIT 1""")	
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			if data == "fml":	
				cursor.execute("""INSERT INTO cloud_fml
						VALUES (%s, CURRENT_TIMESTAMP,%s, 0, %s,%s)
						""", (body,last_titan_id,lang,uid)) 
			else:
				cursor.execute("""INSERT INTO cloud_translate
						VALUES (%s, CURRENT_TIMESTAMP,%s, 0, %s,%s)
						""",(body,last_titan_id,lang,uid))	
			output = "Post Success!"
		self.write(output)
	def get(self, req_id):
		if ( req_id == "info.json"):
			info_since = int(self.get_argument('since'))	
			info_lang = str(self.get_argument('lang'))
			cursor.execute("""
					SELECT iid FROM cloud_info
					WHERE info_lang = %s
					ORDER BY iid DESC
					LIMIT 1	
					""",info_lang)
			row = cursor.fetchone()
			last_id = row[0]
			if ( int(info_since) <= 0 ):
				cursor.execute("""
						SELECT author, title, iid, time, rank
						FROM cloud_info
						WHERE info_lang = %s
						ORDER by time DESC
						LIMIT 30	
						""",info_lang)
				rows = cursor.fetchall()
				new_tweet = len(rows)	
				output = []
				output.append({'info_diff':0,
						'new_tweet':new_tweet})	
				for row in rows:
					output.append({'author':row[0],
							'title':row[1],
							'id':row[2],
							'time':str(row[3])[-8:],
							'rank':row[4]})		
			else:	
				id_diff = last_id - int(info_since)	
				if ( id_diff > 0 ):
					cursor.execute("""
							SELECT author, title, iid, time, rank
							FROM cloud_info
							WHERE iid  > %s
							AND info_lang = %s
							ORDER BY time DESC	
							""",(info_since,info_lang))		
					rows = cursor.fetchall()	
					new_tweet = len(rows)	
					output = []
					output.append({'info_diff':id_diff,
							'new_tweet':new_tweet})	
					for row in rows:		
						output.append({'author':row[0],
								'title':row[1],
								'id':row[2],
								'time':str(row[3]),
								'rank':row[4]})       
        			else:
					output = []	
					output.append({'info_diff' : 0})
		elif ( req_id == 'ranking.json' ):
			rank_lang = str(self.get_argument('lang'))
			cursor.execute("""
					SELECT author, title, iid, time, rank
					FROM cloud_info
					WHERE info_lang = %s	
					ORDER BY rank DESC
					LIMIT 10	
					""",rank_lang)
			rows = cursor.fetchall()
			output = []
			for row in rows:
				output.append({'author':row[0],
						'title':row[1],
						'id':row[2],
						'time':str(row[3]),
						'rank':row[4]})	
		else:
			output = 0	
		self.write(json.dumps(output, indent=4 ))

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "cloud")
}
	
application = tornado.web.Application([
	(r"/", MainHandler),
	(r"/json/(.*)", InfoHandler),
	(r"/chat",ChatHandler),
	(r"/forum/(.*)",ForumHandler),
	(r"/titan/(.*)",AdminBlogHandler),
	],**settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
